package com.atguigu.gmall.mq.receiver;


import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ConsumerMessage {

    /*@RabbitListener(queues = "queues1")
    public void message1(String message){
        System.out.println("queues1 : " + message);
    }*/
    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(name = "queues2",durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = "exchange222"),
            key = {"routingKey222"}
    )})
    public void message2(String msg, Message message, Channel channel){

        try {
            System.out.println("queues2 : " + msg);
            int i = 1/0;
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            if (!message.getMessageProperties().isRedelivered()) {
                System.out.println("消息已经是第一次来了：还可以再处理");
                try {
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }else {
                System.out.println("消息已经是第二次来了：还是没有处理好：只能拒绝了");
                try {
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }
}
